package com.jose.photogallery;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.jose.photogallery.domain.PhotogalleryDAO;
import com.jose.photogallery.domain.Photo;
import com.jose.photogallery.domain.UploadUtil;

@SuppressWarnings("serial")
public class EditPhotoServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(EditPhotoServlet.class
			.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		// Parameters
		String blobKey = req.getParameter("key");

		PhotogalleryDAO dao = new PhotogalleryDAO();
		// Get the photo
		Photo photo = dao.getPhoto(blobKey);

		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		// User validation
		if (user != null) {
			String logoutUrl = userService.createLogoutURL("/");
			req.setAttribute("logoutUrl", logoutUrl);
			req.setAttribute("user", user);

			// Photo and Ownership validation
			if (photo != null && photo.getUser().equals(user.getUserId())) {
				log.info("Edit photo with key=" + photo.getBlobKey());
				req.setAttribute("photo", photo);
				req.getRequestDispatcher("/WEB-INF/JSP/editphoto.jsp").forward(req,
						resp);
			} else {
				req.setAttribute("error",
						"Sorry, you dont have permission to access this page!");
				req.getRequestDispatcher("/WEB-INF/JSP/errorpage.jsp").forward(req,
						resp);
			}
		} else {
			System.out.println("local address: " + req.getLocalAddr());
			String loginUrl = userService.createLoginURL("/");
			req.setAttribute("loginUrl", loginUrl);
			req.setAttribute("error",
					"Sorry, you need to login to access this page!");
			req.getRequestDispatcher("/WEB-INF/JSP/errorpage.jsp").forward(req,
					resp);
		}
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		
		PhotogalleryDAO dao = new PhotogalleryDAO();

		Date updateDate = new Date();

		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		// Validate user login
		if (user != null) {
			// Get the photo
			Photo photo = dao.getPhoto(req.getParameter("key"));
			
			// Validates the owner is updating the photo
			if (photo.getUser().equals(user.getUserId())){
				// Forms input fields
				String caption = (String) req.getParameter("caption");
				List<String> tags = UploadUtil.splitInput(req.getParameter("tags"));
				String description = (String) req.getParameter("description");
				String privacy = (String) req.getParameter("privacy");
				
				// Update the Photo
				photo.setCaption(caption);
				photo.setDescription(description);
				photo.setTags(tags);
				photo.setPrivacy(privacy);
				photo.setUpdateDate(updateDate);
				
				dao.savePhoto(photo);
				
				// Show the new uploaded Photo
				resp.sendRedirect("/photo?key=" + photo.getBlobKey());
			} else {
				String logoutUrl = userService.createLogoutURL("/");
				req.setAttribute("logoutUrl", logoutUrl);
				req.setAttribute("user", user);
				req.setAttribute("error", "Sorry, you dont have permission to edit the photo!");
				req.getRequestDispatcher("/WEB-INF/errorpage.jsp").forward(req, resp);
			}
		} else {
			String logoutUrl = userService.createLogoutURL("/");
			req.setAttribute("logoutUrl", logoutUrl);
			req.setAttribute("user", user);
			req.setAttribute("error", "Sorry, you need to be login to access this page!");
			req.getRequestDispatcher("/WEB-INF/errorpage.jsp").forward(req, resp);
		}
	}
}
